use crate::api::model::role::*;
use crate::rpc::client::SystemRpcClient;
use crate::rpc::pb;
use salvo::http::StatusError;
use salvo::prelude::*;
use serde_json::json;
use std::sync::Arc;
use tracing::{error, info, instrument};

pub use super::{Controller, RoleController, convert_tonic_status};

/// 获取角色列表
#[endpoint(
    operation_id = "system_role_getRoleList",
    tags("系统/角色管理"),
    responses(
        (status_code = 200, description = "成功", body = serde_json::Value),
    )
)]
#[instrument(skip(req, res))]
pub async fn get_list(req: &mut Request, res: &mut Response) -> Result<(), StatusError> {
    info!("API: 获取角色列表请求");

    let rpc_client = req
        .extensions()
        .get::<Arc<SystemRpcClient>>()
        .ok_or_else(|| StatusError::internal_server_error().brief("RPC 客户端未初始化"))?;

    // 解析查询参数
    let name = req.query::<String>("name").unwrap_or_default();
    let code = req.query::<String>("code").unwrap_or_default();
    let status = req.query::<i32>("status").unwrap_or(0);
    let parent_id = req.query::<i64>("parent_id").unwrap_or(0);

    let rpc_req = pb::role::GetRoleListReq {
        name,
        code,
        status,
        parent_id,
    };

    match rpc_client.get_role_list(rpc_req).await {
        Ok(rpc_response) => {
            let role_list = rpc_response.into_inner();
            let data = json!({
                "total": role_list.total,
                "code": role_list.code,
                "message": role_list.message,
                "roles_count": role_list.roles.len()
            });

            res.render(Json(json!({
                "success": true,
                "message": "操作成功",
                "data": data
            })));
            Ok(())
        }
        Err(e) => {
            error!("获取角色列表失败: {:?}", e);
            Err(convert_tonic_status(e))
        }
    }
}

/// 获取角色详情
#[endpoint(
    operation_id = "system_role_getRoleInfo",
    tags("系统/角色管理"),
    responses(
        (status_code = 200, description = "成功", body = serde_json::Value),
    )
)]
#[instrument(skip(req, res))]
pub async fn get_role_info(req: &mut Request, res: &mut Response) -> Result<(), StatusError> {
    info!("API: 获取角色详情请求");

    let rpc_client = req
        .extensions()
        .get::<Arc<SystemRpcClient>>()
        .ok_or_else(|| StatusError::internal_server_error().brief("RPC 客户端未初始化"))?;

    let role_id: i64 = req
        .param("role_id")
        .ok_or_else(|| StatusError::bad_request().brief("角色ID参数缺失"))?;

    let rpc_req = pb::role::GetRoleInfoReq { role_id };

    match rpc_client.get_role_info(rpc_req).await {
        Ok(rpc_response) => {
            let role_info = rpc_response.into_inner();
            let data = json!({
                "code": role_info.code,
                "message": role_info.message,
                "has_role": role_info.role.is_some()
            });

            res.render(Json(json!({
                "success": true,
                "message": "操作成功",
                "data": data
            })));
            Ok(())
        }
        Err(e) => {
            error!("获取角色详情失败: {:?}", e);
            Err(convert_tonic_status(e))
        }
    }
}

/// 创建角色
#[endpoint(
    operation_id = "system_role_createRole",
    tags("系统/角色管理-管理员"),
    responses(
        (status_code = 200, description = "创建成功", body = serde_json::Value),
    )
)]
#[instrument(skip(req, res))]
pub async fn create_role(req: &mut Request, res: &mut Response) -> Result<(), StatusError> {
    info!("API: 创建角色请求");

    let rpc_client = req
        .extensions()
        .get::<Arc<SystemRpcClient>>()
        .ok_or_else(|| StatusError::internal_server_error().brief("RPC 客户端未初始化"))?;

    // 这里应该解析 JSON 请求体，暂时使用默认值
    let rpc_req = pb::role::CreateRoleReq {
        name: "".to_string(),
        code: "".to_string(),
        description: "".to_string(),
        parent_id: 0,
        sort: 0,
        status: 0,
        menu_ids: vec![],
        remark: "".to_string(),
    };

    match rpc_client.create_role(rpc_req).await {
        Ok(rpc_response) => {
            let result = rpc_response.into_inner();
            res.render(Json(json!({
                "success": true,
                "message": "角色创建成功",
                "data": {
                    "code": result.code,
                    "message": result.message
                }
            })));
            Ok(())
        }
        Err(e) => {
            error!("创建角色失败: {:?}", e);
            Err(convert_tonic_status(e))
        }
    }
}

/// 更新角色
#[endpoint(
    operation_id = "system_role_updateRole",
    tags("系统/角色管理-管理员"),
    responses(
        (status_code = 200, description = "更新成功", body = serde_json::Value),
    )
)]
#[instrument(skip(req, res))]
pub async fn update_role(req: &mut Request, res: &mut Response) -> Result<(), StatusError> {
    info!("API: 更新角色请求");

    let rpc_client = req
        .extensions()
        .get::<Arc<SystemRpcClient>>()
        .ok_or_else(|| StatusError::internal_server_error().brief("RPC 客户端未初始化"))?;

    let role_id: i64 = req
        .param("role_id")
        .ok_or_else(|| StatusError::bad_request().brief("角色ID参数缺失"))?;

    // 这里应该解析 JSON 请求体，暂时使用默认值
    let rpc_req = pb::role::UpdateRoleReq {
        role_id,
        name: "".to_string(),
        code: "".to_string(),
        description: "".to_string(),
        parent_id: 0,
        sort: 0,
        status: 0,
        menu_ids: vec![],
        remark: "".to_string(),
    };

    match rpc_client.update_role(rpc_req).await {
        Ok(rpc_response) => {
            let result = rpc_response.into_inner();
            res.render(Json(json!({
                "success": true,
                "message": "角色更新成功",
                "data": {
                    "code": result.code,
                    "message": result.message
                }
            })));
            Ok(())
        }
        Err(e) => {
            error!("更新角色失败: {:?}", e);
            Err(convert_tonic_status(e))
        }
    }
}

/// 删除角色
#[endpoint(
    operation_id = "system_role_deleteRole",
    tags("系统/角色管理-管理员"),
    responses(
        (status_code = 200, description = "删除成功", body = serde_json::Value),
    )
)]
#[instrument(skip(req, res))]
pub async fn delete_role(req: &mut Request, res: &mut Response) -> Result<(), StatusError> {
    info!("API: 删除角色请求");

    let rpc_client = req
        .extensions()
        .get::<Arc<SystemRpcClient>>()
        .ok_or_else(|| StatusError::internal_server_error().brief("RPC 客户端未初始化"))?;

    let role_id: i64 = req
        .param("role_id")
        .ok_or_else(|| StatusError::bad_request().brief("角色ID参数缺失"))?;

    let rpc_req = pb::role::DeleteRoleReq {
        role_ids: vec![role_id],
    };

    match rpc_client.delete_role(rpc_req).await {
        Ok(rpc_response) => {
            let result = rpc_response.into_inner();
            res.render(Json(json!({
                "success": true,
                "message": "角色删除成功",
                "data": {
                    "code": result.code,
                    "message": result.message
                }
            })));
            Ok(())
        }
        Err(e) => {
            error!("删除角色失败: {:?}", e);
            Err(convert_tonic_status(e))
        }
    }
}

/// 获取角色树
#[endpoint(
    operation_id = "system_role_getRoleTree",
    tags("系统/角色管理"),
    responses(
        (status_code = 200, description = "成功", body = serde_json::Value),
    )
)]
#[instrument(skip(req, res))]
pub async fn get_role_tree(req: &mut Request, res: &mut Response) -> Result<(), StatusError> {
    info!("API: 获取角色树请求");

    let rpc_client = req
        .extensions()
        .get::<Arc<SystemRpcClient>>()
        .ok_or_else(|| StatusError::internal_server_error().brief("RPC 客户端未初始化"))?;

    let rpc_req = pb::role::GetRoleTreeReq { status: 0 };

    match rpc_client.get_role_tree(rpc_req).await {
        Ok(rpc_response) => {
            let result = rpc_response.into_inner();
            res.render(Json(json!({
                "success": true,
                "message": "操作成功",
                "data": {
                    "code": result.code,
                    "message": result.message,
                    "roles_count": result.roles.len()
                }
            })));
            Ok(())
        }
        Err(e) => {
            error!("获取角色树失败: {:?}", e);
            Err(convert_tonic_status(e))
        }
    }
}

/// 转换角色信息
fn convert_role_info(role: pb::role::RoleInfo) -> RoleInfo {
    RoleInfo {
        id: role.id,
        name: role.name,
        code: role.code,
        description: role.description,
        parent_id: role.parent_id,
        sort: role.sort,
        status: role.status,
        remark: role.remark,
        created_at: role.created_at,
        updated_at: role.updated_at,
        children: vec![],
        menus: role
            .menus
            .into_iter()
            .map(|menu| MenuInfo {
                id: menu.id,
                name: menu.name,
                path: menu.path,
                perm_code: menu.perm_code,
            })
            .collect(),
    }
}

/// 转换角色信息（带子角色）
fn convert_role_info_with_children(role: pb::role::RoleInfo) -> RoleInfo {
    RoleInfo {
        id: role.id,
        name: role.name,
        code: role.code,
        description: role.description,
        parent_id: role.parent_id,
        sort: role.sort,
        status: role.status,
        remark: role.remark,
        created_at: role.created_at,
        updated_at: role.updated_at,
        children: role.children.into_iter().map(convert_role_info).collect(),
        menus: role
            .menus
            .into_iter()
            .map(|menu| MenuInfo {
                id: menu.id,
                name: menu.name,
                path: menu.path,
                perm_code: menu.perm_code,
            })
            .collect(),
    }
}
